---
title: Bun
description: Authentication for Bun's http server
mode: "wide"
---

## Prerequisites

- Created your [Unkey account](https://app.unkey.com/auth/sign-up)
- Created an API in the [Unkey dashboard](https://app.unkey.com/apis)

<Card title="Skip the tutorial" icon="link" href="https://github.com/unkeyed/examples/tree/main/bun-server">
  Don't want to read the tutorial? Click this to get an example ready to test.
</Card>

## Creating a bun server protected by Unkey

<Steps titleSize="h3">
<Step title="Create a new Bun project">
First we need a bun project, so create a new directory and init bun.
```bash
mkdir unkey-with-bun
cd unkey-with-bun
bun init -y
```

</Step>
<Step  title="Install">

Now install the `@unkey/api` package

```bash
bun install @unkey/api@0.35
```

</Step>

<Step title="Modify the server">

Open up the file called `index.ts` and add the following code

```ts index.ts
import { verifyKey } from "@unkey/api";

const server = Bun.serve({
  async fetch(req) {
    const key = req.headers.get("Authorization")?.replace("Bearer ", "");
    if (!key) {
      return new Response("Unauthorized", { status: 401 });
    }

    const { result, error } = await verifyKey(key);
    if (error) {
      // This may happen on network errors
      // We already retry the request 5 times, but if it still fails, we return an error
      console.error(error);
      return Response.json("Internal Server Error", { status: 500 });
    }

    if (!result.valid) {
      return new Response("Unauthorized", { status: 401 });
    }

    return Response.json(result);
  },
  port: 8000,
});
console.log(`Listening on ${server.url}`);
```

</Step>

<Step title="Running the server">

```bash
bun run index.ts
```

</Step>

<Step title="Try it out">

Go to `https://app.unkey.com` and create a new key. Then verify it with our new server:

```bash
curl http://localhost:8000 -H "Authorization: Bearer <KEY>"
```

It should return `{"keyId":"key_id","valid":true,"meta":{},"enabled":true,"permissions":[],"code":"VALID"}` and potentially more information about the key, depending on what you set up in the dashboard.

</Step>

</Steps>

## What is next?

Now that you've seen the power of Unkey, check out some resources below to continue your journey.

<CardGroup cols={3}>
  <Card title="Discord" icon="discord" href="https://unkey.com/discord">Join our Discord to chat with us and the community</Card>
  <Card title="Unkey API Reference" icon="database" href="/api-reference">
     Learn about our API that helps you manage APIs, keys, ratelimits and analytical data.
  </Card>
  <Card title="SDKs" icon="brackets-curly" href="/libraries">
   Check out our SDKs and how they fit into your Bun application.
  </Card>
</CardGroup>
